import { reqCardList, reqDeleteGoods, reqGoodsCheck } from "@/api"

const actions = {
    async getCardInfoList(context) {
        let result = await reqCardList()
        if (result.code === 200) {
            context.commit('CARDLISTINFO', result.data)
        }
    },
    async deleteGoods(context, skuId) {
        let result = await reqDeleteGoods(skuId)
        if (result.code === 200) {
            return 'ok'
        }
        else {
            return Promise.reject(new Error('fail'))
        }
    },
    async updateCheck(context, { skuId, isChecked }) {
        let result = await reqGoodsCheck(skuId, isChecked)
        if (result.code === 200) {
            return 'ok'
        }
        else {
            return Promise.reject(new Error('fail'))
        }
    },
    async deleteSelectGoods(context) {
        let promiseAll = []
        context.getters.cartInfo.cartInfoList.forEach(item => {
            if (item.isChecked == 1) {
                let promise = context.dispatch('deleteGoods', item.skuId)
                promiseAll.push(promise)
            }
        });
        return Promise.all(promiseAll)
    },
    selectAllGoods(context, isChecked) {
        let promiseAll = []
        context.getters.cartInfo.cartInfoList.forEach(item => {
            let promise = context.dispatch('updateCheck', {
                skuId: item.skuId,
                isChecked
            })
            promiseAll.push(promise)
        });
        return Promise.all(promiseAll)
    }
}

const mutations = {
    CARDLISTINFO(state, cardListInfo) {
        state.cardListInfo = cardListInfo
    }

}

const state = {
    cardListInfo: []

}

const getters = {
    cartInfo(state) {
        return state.cardListInfo[0] || {}
    }
}

export default {
    actions,
    mutations,
    state,
    getters
}